<?php

class customerActions extends sfActions {

    public function preExecute() {
        date_default_timezone_set(AppTools::TIMEZONE);
    }

    public function executeList(sfWebRequest $request) {
        $name = $request->getParameter('name', null);
        $this->name = $name;

        $rows = CustomerTable::getList($name);
        $this->rows = $rows;
    }

    public function executeUpdate(sfWebRequest $request) {
        $id = $request->getParameter('id');

        if ($id) {
            $customer = CustomerTable::retrieveByPK($id);
            if (!$customer) {
                $this->getUser()->setFlash('warning', 'Гишүүн олдсонгүй');
                $this->redirect($request->getReferer());
            }
            $flash = 'Амжилттай заслаа';
        } else {
            $customer = new Customer();
            $flash = 'Амжилттай нэмлээ';
        }

        $form = new CustomerForm($customer);

        if ($request->isMethod('post')) {
            $form->bind($request->getParameter('customer'));

            if ($form->isValid()) {
                $form->save();

                $this->getUser()->setFlash('success', $flash);
                $this->redirect('@customer_list');
            }
        }

        $this->form = $form;
        $this->id = $id;
        $this->customer = $customer;
    }

    public function executeChangeState(sfWebRequest $request) {
        $customer = CustomerTable::retrieveByPk($request->getParameter('id'));
        if ($customer) {
            if ($customer->is_active == CustomerTable::ACTIVE) {
                $customer->setIsActive(CustomerTable::PASSIVE);
                $this->getUser()->setFlash('success', 'Амжилттай устгалаа');
            } elseif ($customer->is_active == CustomerTable::PASSIVE) {
                $customer->setIsActive(CustomerTable::ACTIVE);
                $this->getUser()->setFlash('success', 'Амжилттай сэргээлээ');
            }
            $customer->save();
        } else {
            $this->getUser()->setFlash('error', 'Гишүүн олдсонгүй!');
        }

        $this->redirect('@customer_list');
    }

}
